import cv2
import py360convert

# 读取等距柱状投影的球面图
img = cv2.imread("panorama.jpeg")
# 转换为六个立方体面 (face_size 可调，越大越清晰)
face_size = 2048
size = 4

# 检查图像是否成功加载
if img is None:
    exit(1)

print("图像加载成功，开始转换为立方体贴图...")


cube_map = py360convert.e2c(img, face_w=face_size)

print(f"立方体贴图形状: {cube_map.shape}")

# 立方体贴图是按 3行x4列 网格排列的
# 根据py360convert的默认布局进行分割
height = face_size
width = face_size

# 分割立方体贴图为6个独立的面
# 标准布局通常是: [+X, -X, +Y, -Y, +Z, -Z] 或类似的排列
faces = {}

# 按照常见的立方体贴图布局分割
faces['front'] = cube_map[height:2*height, width:2*width]      # 中心位置
faces['right'] = cube_map[height:2*height, 2*width:3*width]    # 右侧
faces['back'] = cube_map[height:2*height, 3*width:4*width]     # 最右
faces['left'] = cube_map[height:2*height, 0:width]             # 最左
faces['top'] = cv2.rotate(cube_map[0:height, width:2*width], cv2.ROTATE_180)               # 上方，旋转180度
faces['bottom'] = cv2.rotate(cube_map[2*height:3*height, width:2*width], cv2.ROTATE_180)   # 下方，旋转180度

# 保存六个面的图片
for name, face in faces.items():
    # 保存原始高分辨率版本
    cv2.imwrite(f"cubemap_{name}.jpg", face)
    print(f"已保存: cubemap_{name}.jpg (尺寸: {face.shape[1]}x{face.shape[0]})")
    
    # 保存低分辨率版本 (512x512)
    face_low = cv2.resize(face, (512, 512), interpolation=cv2.INTER_AREA)
    cv2.imwrite(f"cubemap_{name}_low.jpg", face_low)
    print(f"已保存: cubemap_{name}_low.jpg (尺寸: 512x512)")

print("立方体贴图转换完成！")

# 将每个面分割成2x2的瓦片
print("\n开始分割每个面为2x2瓦片...")

def split_face_to_tiles(face_image, face_name, size=2):
    """将一个立方体面分割成size x size的瓦片"""
    h, w = face_image.shape[:2]
    tile_h = h // size
    tile_w = w // size
    
    tiles = {}
    for row in range(size):
        for col in range(size):
            # 计算瓦片的坐标
            start_y = row * tile_h
            end_y = start_y + tile_h
            start_x = col * tile_w
            end_x = start_x + tile_w
            
            # 提取瓦片
            tile = face_image[start_y:end_y, start_x:end_x]
            
            # 保存瓦片
            tile_filename = f"{face_name}_{col}_{row}.jpg"
            cv2.imwrite(tile_filename, tile)
            tiles[f"{col}_{row}"] = tile_filename
            print(f"已保存瓦片: {tile_filename} (尺寸: {tile.shape[1]}x{tile.shape[0]})")
    
    return tiles

# 为每个面创建瓦片
all_tiles = {}
for face_name, face_image in faces.items():
    print(f"\n分割 {face_name} 面:")
    tiles = split_face_to_tiles(face_image, face_name, size)
    all_tiles[face_name] = tiles

print("\n所有瓦片创建完成！")

